package net.cloudsun.graph.group;

import java.io.InputStream;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

/**
 * 创建群
 * created at 23/11/2021
 *
 * @author 俞建波
 * <a href="mailto://yujianbo@chtwm.com">yujianbo@chtwm.com</a>
 * @since 1.1.0
 */
public abstract class AbstractGroupBuilder<T,G extends FiniteGroup<T>> {

    // 首先从文件里加载所有可用集合
    public Set<G> build(InputStream file) {
        Set<T> availableSet = new HashSet<>();
        try (final Scanner scanner = new Scanner(file)) {
            while (scanner.hasNext()) {
                final String line = scanner.nextLine();
                if (check(line)) {
                    availableSet.add(newElement(line));
                }
            }
        }
        Set<G> groups = new HashSet<>();
        for (T element : availableSet) {
            if (!inGroups(groups, element)) {
                // 创建群, 以自己作为单位元
                final G group = newGroup(element);
                group.setMeta(element);
                // 遍历出集合
                group.buildGroup();
                // 加入groups
                group.adjust(this::compare);
                System.out.println("发现一个新群");
                groups.add(group);
            }
        }
        return groups;
    }

    protected abstract int compare(T t, T t1);
    protected abstract boolean check(String line);
    protected abstract T newElement(String line);
    protected abstract G newGroup(T element);

    private boolean inGroups(Set<G> groups, T jigsawState) {
        for (G group : groups) {
            if (group.getElements().contains(jigsawState)) {
                return true;
            }
        }
        return false;
    }
}
